/**
 * author  bianlongting
 * date    2016-04-26
 * time    14:28
 * description 订单管理
 */

$(function(){
	var order = {
		id			: $(".id"),				//订单id
		sn			: $(".sn"),				//订单号
		mobile		: $(".mobile"),			//手机号
		usermobile	: $(".usermobile"),			//手机号
		consignee	: $(".consignee"),		//收货人
		trace		: $(".trace"),			//来源渠道
		startTime	: $(".startTime"),		//开始时间
		endTime		: $(".endTime"),		//结束时间
		pagesize	: $(".pagesize select"),//每页条数，默认是10
		status		: $(".status"),			//商品状态
		goodContent : $(".good-content"),	//搜索到的商品
		showpage	: $(".showpage"),		//页码
		pageDetail 	: $(".page-detail"),	//页码详情
		checkAll	: $(".checkAll"),		//全选
		btnExport	: $(".btn-export"),		//导出
		btnExportFinance	: $(".btn-export-Finance")		//导出
	};
	var data = {};
	var pageIndex = 1;	//页码默认为第一页
	var pageCount;		//总页码
	var arr = [];
	var search = $(".btn-search");
	data.pagesize 	= order.pagesize.val();
	getData(data);
	search.on("click",function(){
		var startTime = order.startTime.val();
		var endTime = order.endTime.val();
		var mobile = order.mobile.val();
		var usermobile = order.usermobile.val();
		var exc = /^1\d{10}$/;
		if (mobile != "" && !exc.test(mobile)) {
			toast("请填写正确的手机号");
			return false;
		};
		if (usermobile != "" && !exc.test(usermobile)) {
			toast("请填写正确的手机号");
			return false;
		};
		if (startTime != "" && endTime != "") {
			if (new Date(startTime).getTime() > new Date(endTime).getTime()) {
				toast("结束时间必须大于开始时间");
				return false;
			};
		};
		data.id 		= order.id.val();
		data.sn 		= order.sn.val();
		data.consigneemobile 	= mobile;
		data.usermobile 	= usermobile;
		data.consignee 	= order.consignee.val();
		data.trace  	= order.trace.val();
		data.stime 	= order.startTime.val();
		data.etime 	= order.endTime.val();
		data.pagesize 	= order.pagesize.val();
		data.orderstatus= order.status.find('.active').data().status;
		getData(data);
	});

	$(".status li").each( function() {
		$(this).on("click",function(){
			var startTime = order.startTime.val();
			var endTime = order.endTime.val();
			var mobile = order.mobile.val();
			var exc = /^1\d{10}$/;
			if (mobile != "" && !exc.test(mobile)) {
				toast("请填写正确的手机号");
				return false;
			};
			if (startTime != "" && endTime != "") {
				if (new Date(startTime).getTime() > new Date(endTime).getTime()) {
					toast("结束时间必须大于开始时间");
					return false;
				};
			};
			data.id 		= order.id.val();
			data.sn 		= order.sn.val();
			data.mobile 	= mobile;
			data.consignee 	= order.consignee.val();
			data.trace  	= order.trace.val();
			data.startTime 	= order.startTime.val();
			data.endTime 	= order.endTime.val();
			data.pagesize 	= order.pagesize.val();
			data.orderstatus= $(this).data().status;
			getData(data);
		})
	});

	function getData(data) {
		$.ajax({
			url : "/admin/order/orderlist",
			data : data,
			type : 'GET',
			dataType : 'JSON',
			success : function(data){
				if (data.status == true) {
					var data = data.data;
					shopRender(data);		//界面拼装
				} else {
					toast(data.message);
					return false;
				}
			}

		})
	}



	Array.prototype.remove = function(val) {
		//if ($.isArray(val)) {
			var index = this.indexOf(val);
			if (index > -1) {
				this.splice(index, 1);
			}
		//};
	};

	//筛选界面拼装
	function shopRender(param){
		var html = "";
		var orderlist = param.orderlist.data;
		var len = orderlist.length;
		if (len > 0) {
			for (var i = 0; i < len; i++) {
				if(parseInt(orderlist[i].pay_id) == 4){
					payMethod = '支付宝';
				}
				else if(!parseInt(orderlist[i].pay_id)){
					payMethod = '暂未支付';
				}
				else{
					payMethod = '微信';
				}
				var Status = ['', '已下单', '已取消', '已付款', '付款失败', '已清关', '清关失败', '已发货', '已收货'];
				var orderStatusAll = Status[orderlist[i].status];

				html += "<tr>\
                    		<td><input type='checkbox' data-id=" + orderlist[i].order_id +  "> " + orderlist[i].order_id +  "</td>\
                    		<td>" + orderlist[i].order_sn + "</td>\
                    		<td>" + orderlist[i].mobile + "</td>\
                    		<td>" + orderlist[i].consignee + "</td>\
                    		<td>" + orderlist[i].order_time + "</td>\
                    		<td>" + orderlist[i].order_cost + "</td>\
                    		<td>" + payMethod + "</td>";

                	html += "<td>" + orderStatusAll + "</td>";  		 	
                html += 	"<td><a href='/admin/order/orderdetails?orderId=" + orderlist[i].order_id + "' class='btn blue mini'>查看详情</a></td>\
                    	</tr>"
			};
		}else{
			order.goodContent.html("");
		}
		pageCount = param.orderlist.last_page;
		order.goodContent.html(html);
		//页码
		order.showpage.html(param.show);
		//页码详情
		var pageFrom = param.orderlist.from;
		var pageTo = param.orderlist.to;
		if(!param.orderlist.from){
          pageFrom = 0;
		}
		if(!param.orderlist.to){
          pageTo = 0;
		}
		order.pageDetail.html("第" + pageFrom + "~" + pageTo + "条，共计" + param.orderlist.total + "条");
		order.pagesize.on("change",function(){
			data.pagesize = order.pagesize.val();
			pageIndex = data.page = 1;
			$.ajax({
				url : "/admin/order/orderlist",
				data : data,
				type : 'GET',
				dateType : 'JSON',
				success : function(data){
					if (typeof data == 'string') {
						data = JSON.parse(data);
					}
					if (data.status == true) {
						var data = data.data;
						shopRender(data);		//拼装商品
					}else{
						toast(data.message);
					}
				}
			})
		})
		changePage(pageCount);		//切换页码
		order.checkAll.on("click",function(){
            arr = [];
			order.goodContent.find('input').each(function(index, el) {
				if (!$(this).is(':checked')) {
					$(this).prop("checked",true);
					arr.push($(this).data().id);
				}else  {
					arr.push($(this).data().id);
				}
			});
		});
		//导出
		var input = order.goodContent.find('input');
        arr = [];
		input.on("change",function(){
			if ($(this).prop("checked")) {
				arr.push($(this).data().id);
			}else{
				var len = arr.length;
				for (var i = 0; i < len; i++) {
					if (parseInt(arr[i]) == parseInt($(this).data().id)) {
						arr.remove(arr[i])
					};
				};
			}
		})
		order.btnExport.on("click",function(){
			orderExport(arr);
		});
		order.btnExportFinance.on("click",function(){
			orderExportFinance(arr);
		});
	};

	//页码切换
	function changePage(num){
		order.showpage.find('a').on("click",function(e){
			console.log($(this).attr("href").split("page=")[1]);
			e.preventDefault();
			var that = $(this);
			var parent = that.parent();
			data.page = $(this).attr("href").split("page=")[1];
			$.ajax({
				url : "/admin/order/orderlist",
				data : data,
				type : 'GET',
				dateType : 'JSON',
				success : function(data){
					if (typeof data == 'string') {
						data = JSON.parse(data);
					}
					if (data.status == true) {
						console.log(data);
						var data = data.data;
						shopRender(data);		//拼装商品
					}else{
						toast(data.message);
					}
				}
			})
		})
	};
    
    //时间戳转化
	function format(time)
	{
	//shijianchuo是整数，否则要parseInt转换
	var time = new Date(time);
	var y = time.getFullYear();
	var m = time.getMonth()+1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
	}
	function add0(m){return m<10?'0'+m:m }


	//导出函数
	function orderExport(arr){
		if (arr.length > 0) {
			var result = []; 
			for (var i = 0; i < arr.length; i++){
			  	if (result.indexOf(arr[i]) == -1) result.push(arr[i]);
			}
			window.location.href = "/admin/order/custom/export?orderids=" + result.toString();
		}else{
			toast("请选择商品");
		};
	}

	//导出函数
	function orderExportFinance(arr){
		if (arr.length > 0) {
			var result = [];
			for (var i = 0; i < arr.length; i++){
			  	if (result.indexOf(arr[i]) == -1) result.push(arr[i]);
			}
			window.location.href = "/index.php?m=Home&c=OrderNew%2FIndex&a=orderExportFinance&orderids=" + result.toString();
		}else{
			toast("请选择商品");
		};
	}

	//toast提示函数
    function toast(tip){
        $(".toast_tip").html(tip);
        $(".toast").fadeIn('1000');
        setTimeout(function(){
            $(".toast").fadeOut();
        },1000);
        return false;
    }
});